<template>
	<view class="main" @touchstart.stop>
		<!-- 商家图片轮播 -->
		<view class="shop-images">
			<!-- 修改 v-if 条件，避免使用可选链操作符 -->
			<swiper v-if="shopInfo && shopInfo.photos && shopInfo.photos.length > 0" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" class="shop-swiper">
				<swiper-item v-for="(item, index) in shopInfo.photos" :key="index">
					<image :src="item.url" mode="aspectFill" class="swiper-image"></image>
				</swiper-item>
			</swiper>
			<view v-else class="no-image-placeholder">
				<text>暂无图片</text>
			</view>
		</view>

		<!-- 商家基本信息 -->
		<view class="shop-details">
			<view class="item" v-if="shopInfo && shopInfo.title">
				<text class="value" style="font-size: 32rpx; font-weight: 600">{{ shopInfo.title }}</text>
			</view>
			<!-- 距离信息 -->
			<view class="item" v-if="shopInfo && shopInfo.location">
				<text class="label">离您：</text>
				<text class="value">{{ shopInfo && shopInfo.location ? getDistance(shopInfo.location) : '距离未知' }}</text>
			</view>

			<!-- 电话信息 -->
			<view class="item" v-if="shopInfo && shopInfo.tel">
				<text class="label">电话：</text>
				<text class="value">{{ shopInfo && shopInfo.tel ? shopInfo.tel : '暂无电话' }}</text>
			</view>

			<!-- 地址信息 -->
			<view class="item" v-if="shopInfo && shopInfo.address">
				<text class="label">地址：</text>
				<text class="value">{{ shopInfo && shopInfo.address ? shopInfo.address : '暂无地址' }}</text>

				<uni-icons type="location-filled" size="30" color="#0055ff" @click.stop="navigator(shopInfo)"></uni-icons>
			</view>
		</view>

		<!-- 操作按钮 -->
		<view class="action-buttons">
			<view class="btn" @click="handerBtn('reserve')">
				<uni-icons type="auth-filled" size="30" color="#5500ff"></uni-icons>
				<text class="btntxt">预约</text>
			</view>
			<view class="btn" @click="handerChat(shopInfo.sendUserId)">
				<uni-icons type="chatboxes" size="30" color="#aaaaff"></uni-icons>
				<text class="btntxt">聊天</text>
			</view>
			<view class="btn" @click="handlePhone(shopInfo.tel)">
				<uni-icons type="phone-filled" size="30" color="#00aa00"></uni-icons>
				<text class="btntxt">电话</text>
			</view>
		</view>

		<!-- 关闭按钮 -->
		<view class="close-btn" @click="handleClose">
			<uni-icons type="close" size="30"></uni-icons>
		</view>
	</view>
</template>

<script>
const db = uniCloud.databaseForJQL();


import { distance_m } from '../utils/distance';

export default {
	name: 'shopinfo',
	props: {
		shopInfoId: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			isLoading: false,
			shopInfo: null,
			errorMsg: ''
		};
	},
	watch: {
		shopInfoId: {
			handler(newval) {
				if (newval) {
					this.getShopInfo(newval);
				}
			},
			immediate: true
		}
	},
	mounted() {
		this.getShopInfo(this.shopInfoId);
	},
	methods: {
		// 计算距离
		getDistance(location) {
			try {
				const loc = {
					longitude: location.coordinates[0],
					latitude: location.coordinates[1]
				};

				return distance_m(this.$store.state.msg.senderLocation, loc);
			} catch (error) {
				console.error('计算距离出错:', error);
				return '距离计算失败';
			}
		},

		// 获取商家信息
		async getShopInfo(id) {
			this.isLoading = true;
			this.errorMsg = '';

			try {
				const res = await db
					.collection('sendshop')
					.where({
						sendshopId: id
					})
					.get();

				if (res.data && res.data.length > 0) {
					this.shopInfo = res.data[0];
					console.log('商家信息:', this.shopInfo);
				} else {
					this.errorMsg = '未找到商家信息';
					console.warn('未找到商家信息');
				}
			} catch (error) {
				this.errorMsg = '获取商家信息失败';
				console.error('获取商家信息失败:', error);
			} finally {
				this.isLoading = false;
			}
		},

		// 关闭弹窗
		handleClose() {
			this.$emit('close');
		},
        handlePhone(phone){
			if(!phone){
				uni.showToast({
				title:'暂无电话',
				icon:'none',
				position:'center'
				})
				return
			}
			uni.makePhoneCall({
				phoneNumber:phone
			})
		},
		handerChat(userId){
			if(!userId){
					uni.showToast({
								title:'店家未开放聊天',
								icon:'none',
								position:'center'
								})
								return
			}
			uni.navigateTo({
				url:`/pages/PrivateChat/PrivateChat?id=${userId}`
			})
		},
	navigator(shopInfo) {
	  // 1. 严格校验参数格式
	  if (!shopInfo?.location?.coordinates ||shopInfo?.location?.coordinates.length !== 2) {
	    uni.showToast({ title: "位置信息无效", icon: "none" });
	    return;
	  }
	
	  // 2. 提取经纬度（注意顺序：确认 coordinates 是 [纬度, 经度] 还是 [经度, 纬度]）
	  // 假设 coordinates 是 [longitude, latitude]（先经后纬，需交换顺序）
	  const longitude =shopInfo.location.coordinates[0]; // 经度
	  const latitude =shopInfo.location.coordinates[1]; // 纬度
	
	  // 3. 校验经纬度是否为有效数字
	  if (typeof latitude !== "number" || typeof longitude !== "number" || isNaN(latitude) || isNaN(longitude)) {
	    uni.showToast({ title: "经纬度格式错误", icon: "none" });
	    return;
	  }
	
	  // 4. 调起地图导航，补充显示信息和错误处理
	  uni.openLocation({
	    latitude: latitude, // 纬度（必填）
	    longitude: longitude, // 经度（必填）
	    name: shopInfo.title || "目标地点", // 地点名称（可选，提升用户体验）
	    address: shopInfo.address || "未知地址", // 详细地址（可选）
	    scale: 16, // 地图缩放级别（3-20，建议16级）
	    success: () => {
	      console.log("导航已成功调起");
	    },
	    fail: (err) => {
	      console.error("调起导航失败：", err);
	      // 根据错误类型提示用户
	      if (err.errMsg.includes("auth deny")) {
	        uni.showToast({ title: "请授予位置权限后重试", icon: "none" });
	      } else {
	        uni.showToast({ title: "调起导航失败，请检查地图应用", icon: "none" });
	      }
	    }
	  });
	},
		// 处理按钮点击
		handerBtn(type) {
	
			uni.showModal({
				title: '商家未注册',
				content: '商家未开通此功能，如果您是商家请联系就近管家',
				success(res) {
					if (res.confirm) {
						// 用户点击确认后的操作
					}
				}
			});
		}
	}
};
</script>

<style scoped>
.main {
	position: fixed;
	top: 200rpx;
	left: 75rpx;
	width: 600rpx;
	padding: 32rpx;
	background-color: #ffffff;
	border-radius: 32rpx;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
	z-index: 100;
}

.shop-images {
	width: 536rpx;
	height: 300rpx;
	margin-bottom: 20rpx;
	border-radius: 16rpx;
	overflow: hidden;
}

.shop-swiper {
	width: 536rpx;
	height: 300rpx;
}

.swiper-image {
	width: 750rpx;
	height: 300rpx;
}

.no-image-placeholder {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 536rpx;
	height: 300rpx;
	background-color: #f5f5f5;
	color: #999;
	font-size: 28rpx;
}

.shop-details {
	margin-bottom: 20rpx;
}

.item {
	display: flex;
	flex-direction: row;
	align-items: center;
	margin-bottom: 16rpx;
	padding: 0 16rpx;
}

.label {
	/* #ifndef APP-PLUS-NVUE */
	flex-grow: 0;
	flex-shrink: 0;
	/*    #endif */
	display: flex;
	flex-direction: column;
	width: 100rpx;

	color: #666;
	font-size: 28rpx;
}

.value {
	flex: 1;
	color: #333;
	font-size: 28rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	display: flex;
	/* 使用 flex 替代 -webkit-box */
	flex-direction: column;
	/* #ifndef APP-PLUS-NVUE */
	line-clamp: 1;
	-webkit-line-clamp: 1;
	word-break: break-all;
	/* #endif */
	display: flex;
	flex-direction: column;
}

.icon {
	width: 40rpx;
	height: 40rpx;
	margin-left: 10rpx;
}

.action-buttons {
	display: flex;
	flex-direction: row;
	justify-content: space-around;
	align-items: center;
	padding: 10rpx 0;
}

.btn {
	display: flex;
	justify-content: center;
	align-items: center;
	width: 120rpx;
	height: 120rpx;
	border-radius: 60rpx;
	color: white;
	font-size: 28rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	transition-property: transform, box-shadow;
	/* 替换原来的 transition-property: all; */
	transition-duration: 0.3s;
}
.btntxt {
	font-size: 28rpx;
}

.btn:active {
	transform: scale(0.95);
	box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
}

.close-btn {
	position: absolute;
	top: 10rpx;
	right: 10rpx;
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 30rpx;
	background-color: white;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	z-index: 10;
	transition-property: transform;
	/* 替换原来的 transition-property: all; */
	transition-duration: 0.3s;
}

.close-btn:active {
	transform: rotate(90deg);
}
</style>
